﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace DynaBoard
{
    public partial class Vote
    {
        public static int Count(int postId)
        {
            using (var db = DynaBoardDataContext.Create)
            {
                var votes = from vote in db.Vote
                            where vote.PostId == postId
                            select vote.Vote1;

                if (votes.Count() == 0)
                {
                    return 0;
                }

                return votes.Sum();
            }
        }

        public static void Register(int postId, RequestorAddress user, int vote)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            if (vote != -1 && vote != 1)
            {
                throw new ArgumentOutOfRangeException("Vote must be either -1 or 1");
            }

            using (var db = DynaBoardDataContext.Create)
            {
                var previousVote = (from v in db.Vote
                                    where v.Ip == user.ToString() &&
                                          v.PostId == postId 
                                    select v).SingleOrDefault();

                if (previousVote == null)
                {
                    db.Vote.InsertOnSubmit(new Vote()
                    {
                        Ip = user.ToString(),
                        PostId = postId,
                        Vote1 = vote
                    });
                }
                else
                {
                    previousVote.Vote1 = vote;
                }

                db.SubmitChanges();
            }
        }
    }
}
